from rest_framework.views import APIView
from django.http import HttpResponse
import os,json
from os import listdir
class Looking(APIView):
    def post(self, request, *args, **kwargs):
        ip = request.META.get("REMOTE_ADDR")
        myFile = request.FILES.get('file')
        file_name = myFile.name
        new_path = './json_list/' + ip + '/'
        try:
            if not os.path.exists(new_path):
                os.mkdir(new_path)
        except:
            pass
        with open(new_path + file_name, "w+", encoding='utf-8') as f:
            txt = myFile.read().decode('utf8')
            f.write(txt)
            f.close()
        return HttpResponse(content=ip)
    def get(self, request, *args, **kwargs):
        data = request.query_params
        ip = data.get('ip')
        new_path = './json_list/' + ip + '/'
        filename=listdir(new_path)
        if 'algorithm_output.json' in filename and 'input.json' in filename:
            with open(new_path + r'algorithm_output.json', "r", encoding='utf-8') as f:
                txt1=f.read()
                txt1 = json.loads(txt1)
                f.close()
            with open(new_path + r'input.json', "r", encoding='utf-8') as s:
                txt2=s.read()
                txt2 = json.loads(txt2)
                s.close()
            txt3=txt2['image_list']
            img_url = { i['image_id']:i['image_url'] for i in txt3 }
            txt4=txt1['kv_list']
            imgid_list = []
            for i in txt4:
                for y in i['document_list'][0]['content']:
                    if y['image_id'] in img_url:
                        imgid_list.append(y['image_id'])
                        y['image_id'] = img_url[y['image_id']] + '^' + i['document_label']
                    else:
                        y['image_id'] = ""
            img_list = [{ 'img_url':v,'result_list':[],'seq':'未提取文档' } for k,v  in img_url.items() if k not in imgid_list]
            txt5 = {}
            for n in txt4:
              for m in n['document_list'][0]['content']:
                 if len(m['image_id']) != 0:
                    for i in m['value_info']:
                        i.update({'file_name':m['document_field']})
                    txt5.setdefault(m['image_id'],[]).append(m['value_info'])
            txt6=[ {'img_url':k.split('^')[0],'result_list':v,'seq':k.split('^')[1]}for k,v in txt5.items()]
            txt7 = txt6 + img_list
            for i in filename:
                c_path = os.path.join(new_path, i)
                os.remove(c_path)
            return HttpResponse(json.dumps(txt7),content_type='application/json')
        else:
            for i in filename:
                c_path = os.path.join(new_path, i)
                os.remove(c_path)
            return HttpResponse(status=404)
    def put(self, request, *args, **kwargs):
        data = request.data
        key = data['key']
        value_list = data['value']
        result_list = []
        for i in value_list:
            if key in i.values():
                result = i['result_list']
                for y in result:
                    for q in y:
                        name_list = [ s['file_name'] for s in result_list]
                        if q['file_name'] not in name_list:
                            result_list.append({'file_name': q['file_name'],'score_list':[round(q['score'],2)],'field_content':[q['field_content']]})
                        else:
                            index = name_list.index(q['file_name'])
                            result_list[index]['score_list'].append(round(q['score'],2))
                            result_list[index]['field_content'].append(q['field_content'])
            else:
                continue

        return HttpResponse(json.dumps(result_list),content_type='application/json')